//
//  RVLoginViewController.m
//  RememberVocabularies
//
//  Created by 伍银荣 on 2017/10/10.
//  Copyright © 2017年 WYR. All rights reserved.
//

#import "RVLoginViewController.h"
#import <SMS_SDK/SMSSDK.h>
#import "SVProgressHUD.h"
#import "RVMyViewController.h"

@interface RVLoginViewController ()
@property (strong, nonatomic) IBOutlet UITextField *phoneNumTF;

@property (strong, nonatomic) IBOutlet UITextField *securityCodeTF;
@property (strong, nonatomic) IBOutlet UIButton *sendCodeBtn;
@property (nonatomic,strong) NSTimer *timer;
@property (nonatomic,assign) NSInteger time;

@end

@implementation RVLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"手机短信快捷登录";
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(upDate) userInfo:nil repeats:YES];
    
    [_timer setFireDate:[NSDate distantFuture]];
    _time = 59;
    
}

-(void)upDate
{
    _time --;
    [_sendCodeBtn setTitle:[NSString stringWithFormat:@"%lds",_time] forState:UIControlStateNormal];
    if (_time == 0) {
        [_sendCodeBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
        _time = 59;
        [_timer setFireDate:[NSDate distantFuture]];
        //销毁定时器
        //[_timer invalidate];
    }
    
}

- (IBAction)sendCodeBtn:(id)sender {
    if ([_phoneNumTF.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"请填写正确的手机号"];
    }else{
        [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:_phoneNumTF.text zone:@"86" result:^(NSError *error) {
            if (!error) {
                [SVProgressHUD showSuccessWithStatus:@"验证码已发送"];
                [_timer setFireDate:[NSDate distantPast]];
            }else{
                [SVProgressHUD showSuccessWithStatus:@"验证码发送失败"];
            }
        }];
    }
}

- (IBAction)loginBtn:(id)sender {
    if ([_securityCodeTF.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"请填写正确的验证码"];
    }else{
        NSLog(@"%@:%@",_phoneNumTF.text,_securityCodeTF.text);
        [SMSSDK commitVerificationCode:_securityCodeTF.text phoneNumber:_phoneNumTF.text zone:@"86" result:^(NSError *error) {
            if (!error) {
                [SVProgressHUD showSuccessWithStatus:@"验证成功，正在登录。。。"];
                //保存登录成功后的电话号码
                [[NSUserDefaults standardUserDefaults] setObject:_phoneNumTF.text forKey:@"phoneNum"];
                [self.navigationController popViewControllerAnimated:YES];
                //[self.timer invalidate];
            }else{
                [SVProgressHUD showErrorWithStatus:@"验证失败，请重新验证"];
            }
        }];
    }
}




- (IBAction)wechatBtn:(id)sender {
    
}

- (IBAction)QQBtn:(id)sender {
    
}

- (IBAction)blogBtn:(id)sender {
}



-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //点击屏幕，结束编辑
    [self.view endEditing:YES];
}

@end
